package com.alameda.utils;

import com.alameda.base.constant.LoginConstant;

import java.util.Map;

/**
 * ThreadLocal 工具类
 *
 * @author Lv
 * @date 2024/2/19
 */
@SuppressWarnings("all")
public class ThreadLocalUtils {
    /**
     * 提供ThreadLocal对象
     */
    private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();

    /**
     * 根据键获取值
     *
     * @param <T> 泛型
     * @return
     */
    public static <T> T get() {
        return (T) THREAD_LOCAL.get();
    }

    /**
     * 存储键值对
     *
     * @param value 值
     */
    public static void set(Object value) {
        THREAD_LOCAL.set(value);
    }

    /**
     * 清除ThreadLocal 防止内存泄漏
     */
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    /**
     * 获取当前登录用户id
     *
     * @return
     */
    public static Long getUserId() {
        Integer id = null;
        try {
            Map<String, Object> map = getParseResult();
            String value = String.valueOf(map.get(LoginConstant.ID));
            id = Integer.parseInt(value);
        } catch (Exception e) {
            // 处理访问白名单路径场景
            id = 1;
        }

        return id.longValue();
    }

    /**
     * 获取当前登录用户名
     *
     * @return
     */
    public static String getUserName() {
        Map<String, Object> map = getParseResult();
        return (String) map.get(LoginConstant.USERNAME);
    }

    /**
     * 获取当前登录token
     *
     * @return
     */
    public static String getToken() {
        Map<String, Object> map = getParseResult();
        return (String) map.get(LoginConstant.TOKEN);
    }

    /**
     * 获取jwt解析结果
     *
     * @return
     */
    public static Map<String, Object> getParseResult() {
        return ThreadLocalUtils.get();
    }

    /**
     * 设置当前用户id (测试方法使用)
     *
     * @param id 用户id
     */
    public static void setUserId(long id) {
        Map<String, Object> map = MapUtils.newHashMap();
        map.put(LoginConstant.ID, id);
        set(map);
    }
}
